using System.Collections.Generic;
using SimpleJSON;
using UnityEngine;

namespace Gj
{
    public class SelectListHelper : NodeHelper
    {
        public GameObject item;
        public bool simple;
        [SelectRef(UIKey.DATA_KEY)] public SelectKey selectKey;
        private JSONArray actionList;
        private readonly List<SwitchHelper> list = new();

        protected override BindDataType bindDataType => BindDataType.List;

        protected override void BindData(JSONArray array)
        {
            if (list.Count > array.Count)
                for (var index = array.Count; index < list.Count; index++)
                {
                    Destroy(list[index].gameObject);
                    list.RemoveAt(index);
                }
            else
                for (var index = list.Count; index < array.Count; index++)
                {
                    var obj = Instantiate(item, gameObject.transform);
                    obj.SetActive(true);
                    var helper = obj.GetComponent<SwitchHelper>();
                    list.Add(helper);
                    helper.SetIndex(index);
                    // helper.OnChange((int i, bool b) => { ChangeSelect(i, b); });
                }

            actionList = new JSONArray();
            if (selectKey.IsEmpty()) return;
            if (simple)
                actionList.Add(selectKey.Get(_data).AsInt);
            else
                actionList = selectKey.Get(_data).AsArray;

            for (var i = 0; i < actionList.Count; i++)
            {
                var index = actionList[i].AsInt;
                if (list.Count > index)
                    list[index].SetData(true);
            }
        }

        private void ChangeSelect(int index, bool b)
        {
            if (simple)
            {
                if (b) Change(index);
            }
            else
            {
                var selectIndex = -1;
                for (var i = 0; i < actionList.Count; i++)
                    if (actionList[i].AsInt == index)
                        selectIndex = i;
                if (b) actionList.Add(index);
                if (!b) actionList.Remove(selectIndex);
                Change(actionList);
            }
        }
    }
}